<?php

/**
 *
 * @author yupoxiong<i@yupoxiong.com>
 */


declare(strict_types=1);

namespace app\index\controller;

use app\common\model\Adjust;
use app\common\model\ApiLog;
use app\common\model\Channel;
use app\common\model\Country;
use app\common\model\Page;
use app\common\model\Promotion;
use app\common\model\User;
use think\facade\Log;
use think\Request;

class RestController
{
    /**
     * adjust adid数据入库
     */
    public function index(Request $request)
    {
        $adcode = $request->param('aid');
        $usercode = $request->param('uid');
        if (!isset($adcode) || !isset($usercode) || !$adcode) {
            return json(['success' => 0, 'value' => [], 'message' => '参数错误', 'errCode' => 400]);
        }
        Log::write('app-得到adid后1,参数:' . json_encode($request->param()), 'info');
        //判断adjust数据
        $adjustModel = new Adjust();
        $adarr = $adjustModel->where('adid', $adcode)->order('id desc')->find();
        if (!($adarr)) {
            $getid = $adjustModel->insert([
                'adid' => $adcode,
                'create_time' => time(),
            ], false, true);
        } else {
            $getid = $adarr['id'];
        }
        Log::write('app-得到adid后2,操作adjust:' . $getid, 'info');

        if ($usercode) {
            User::where('usercode', $usercode)->update([
                'adid' => $adcode,
            ]);
        }
        return json(['success' => 1, 'value' => ['isvalid' => 0, 'isSubscriber' => 0], 'message' => 'success', 'errCode' => 200]);
    }

    /**
     * 判断显示a/b面
     */
    public function result(Request $request)
    {
        $usercode = $request->param('uid');
        $appcode = $request->param('appid');
        if (!isset($appcode) || !isset($usercode)) {
            return json(['success' => 0, 'value' => [], 'message' => '参数错误', 'errCode' => 400]);
        }
        Log::write('app-获取url接口1，参数：' . json_encode($request->param()), 'info');
        $channel_arr =  Channel::where('number', $appcode)->find(); //判断包是否错误
        Log::write('app-获取url接口2，channel包信息：' . json_encode($channel_arr), 'info');
        if (!$channel_arr) {
            return  json(['success' => 0, 'value' => [], 'message' => '没有该渠道', 'errCode' => 400]);
        }
        $success = 200;
        $url = '';
        $user_arr = User::where('usercode', $usercode)->find();
        if (!$user_arr) {
            $success = 300;
            User::create(['usercode' => $usercode, 'appcode' => $appcode]);
        } else {
            $adjust_arr = Adjust::where('adid', $user_arr['adid'])->find();
            if (isset($adjust_arr['tracker_name'])) { //是否有归因数据
                if ($adjust_arr['tracker_name'] != 'Organic' && $adjust_arr['tracker_name'] != '') {
                    Log::write('app-获取url接口3，adjust信息：' . json_encode($adjust_arr), 'info');

                    $channel_arr = Channel::where('number', $user_arr['appcode'])->find();
                    $promotion_arr = Promotion::where(['channel_id' => $channel_arr['id'], 'country' => $adjust_arr['country']])->find();
                    if ($promotion_arr) {
                        $page_arr = Page::where('id', $promotion_arr['page_id'])->find();
                        if ($page_arr) {
                            $success = 100;
                            $url = 'https://www.' . $page_arr['domain'] . '/h_' . $page_arr['keys'] . '.html?usercode=' . $usercode.'&appid='.$appcode;  //B面地址
                        }
                    }
                }
            }
        }
        Log::write('app-获取url接口1，返回信息：status:' . $success . '  url:' . $url, 'info');
        return json([
            'success' => 1,
            'value' => [
                'status' => $success,
                'url' => $url,
            ],
            'message' => 'success',
            'errCode' => 200
        ]);
    }

    /** 注册接口 */
    public function register(Request $request)
    {
        $mobile = $request->param('mobile');
        $uid = $request->param('uid');
        if (!isset($mobile) || !isset($uid)) {
            return json(['success' => 0, 'value' => [], 'message' => '参数错误', 'errCode' => 400]);
        }
        if ($mobile == '12344321') {
            return json(['code' => 300, 'msg' => '注册成功']);
        }
        Log::write('注册入口1：' . json_encode($request->param()), 'info');
        $data = [
            'mobile' => $mobile,
            'nickname' => '用户' . rand(10000, 99999),
            'avatar' => '/static/images/avatar.png',
            'create_time' => time(),
        ];
        $res = User::where('usercode', $uid)->update($data);
        Log::write('注册入口2，改user表：' . json_encode($res), 'info');
        if ($res) {
            return json([
                'success' => 0,
                'value' => [],
                'message' => '注册成功',
                'errCode' => 200
            ]);
        } else {
            return json([
                'success' => 1,
                'value' => [],
                'message' => '注册失败',
                'errCode' => 400
            ]);
        }
    }
    /** 判断归因数据 */
    public function isab(Request $request)
    {
        $uid = $request->param('uid');
        if (!isset($uid)) {
            $result = ['success' => 0, 'value' => [], 'message' => '参数错误', 'errCode' => 400];
            Log::write('归因判断返回1：' . json_encode($result), 'info');
            return json($result);
        }
        $res = User::where('usercode', $uid)->find();
        Log::write('归因1，用户：' . json_encode($res), 'info');
        if ($res) {
            $adid = $res['adid'];
            if ($adid) {
                $adres = Adjust::where('adid', $adid)->find();
                Log::write('归因2，adjust：' . json_encode($adres), 'info');
                if ($adres['content'] != '') {

                    if ($adres['tracker_name'] == 'Organic' || $adres['tracker_name'] == '') {
                        $result = [
                            'success' => 1,
                            'value' => [
                                'status' => 100
                            ],
                            'message' => '请显示A',
                            'errCode' => 200
                        ];
                        Log::write('归因判断返回2：' . json_encode($result), 'info');
                        return json($result);
                    }
                    $channel_arr = Channel::where('number', $res['appcode'])->find();
                    $promotion_arr = Promotion::where(['channel_id' => $channel_arr['id'], 'country' => $adres['country']])->find();
                    if (!$promotion_arr) {
                        $result = [
                            'success' => 1,
                            'value' => [
                                'status' => 100
                            ],
                            'message' => '请显示A',
                            'errCode' => 200
                        ];
                        Log::write('归因判断返回3：' . json_encode($result), 'info');
                        return json($result);
                    }
                    $page_arr = Page::where('id', $promotion_arr['page_id'])->find();
                    if ($page_arr) {
                        $url = 'https://www.' . $page_arr['domain'] . '/h_' . $page_arr['keys'] . '.html?usercode=' . $uid.'&appid='.$res['appcode'];  //B面地址
                        $result = [
                            'success' => 1,
                            'value' => [
                                'status' => 200,
                                'url' => $url,
                            ],
                            'message' => '请显示B',
                            'errCode' => 200
                        ];
                        Log::write('归因判断返回4：' . json_encode($result), 'info');
                        return json($result);
                    }
                } else {
                    $result = [
                        'success' => 1,
                        'value' => [
                            'status' => 300
                        ],
                        'message' => '请显示等待页',
                        'errCode' => 200
                    ];
                    Log::write('归因判断返回5：' . json_encode($result), 'info');
                    return json($result);
                }
            } else {
                $result = [
                    'success' => 1,
                    'value' => [
                        'status' => 300
                    ],
                    'message' => '请显示等待页',
                    'errCode' => 200
                ];
                Log::write('归因判断返回6：' . json_encode($result), 'info');
                return json($result);
            }
        }
        $result = [
            'success' => 1,
            'value' => [
                'status' => 100
            ],
            'message' => '请显示A',
            'errCode' => 200
        ];
        Log::write('归因判断返回7：' . json_encode($result), 'info');
        return json($result);
    }

    /** 国家列表 */
    public function countryList()
    {
        $data = Country::where('code !=""')->field('code,name,smscode,en_name')->select();
        return json(
            [
                'success' => 1,
                'value' => $data,
                'message' => '获取成功',
                'errCode' => 200
            ]
        );
    }
}
